package com.chendechao.model_home.ui.recommend

import android.widget.Toast
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chendechao.lib_base.BaseActivity
import com.chendechao.model_home.databinding.ActivityRecommendBinding
import com.chendechao.model_home.model.RecommendMutilVideo
import com.chendechao.model_home.ui.recommend.comment.CommentIntent
import com.chendechao.model_home.ui.recommend.comment.CommentUIState
import com.chendechao.model_home.ui.recommend.comment.CommentViewModel
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.PlaybackException
import com.google.android.exoplayer2.Player
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class RecommendActivity : BaseActivity<ActivityRecommendBinding, CommentViewModel>(ActivityRecommendBinding::inflate) {
    override val viewModel: CommentViewModel by viewModels()
    //评论
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: CommentAdapter
    override fun initView() {
        // 获取传递的数据
        val videoData = intent.getParcelableExtra<RecommendMutilVideo>("video_data")
        videoData?.let {
            // 在这里处理接收到的数据
            // 例如：更新UI显示视频详情
            val player = ExoPlayer.Builder(this).build()
            binding.playerView.player = player

            // 设置播放错误监听器
            player.addListener(object : Player.Listener {
                override fun onPlayerError(error: PlaybackException) {
                    Toast.makeText(this@RecommendActivity, "视频播放失败", Toast.LENGTH_SHORT).show()
                }
            })

            val mediaItem = MediaItem.fromUri(it.videopath)
            player.setMediaItem(mediaItem)
            player.prepare()
            player.play()

            binding.videoTitle.setText(it.toutiaolvideotext)
        }

        //评论
        viewModel.sendEvent(CommentIntent.LoadData)

        recyclerView = binding.commentRecyclerView
        recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = CommentAdapter()//初始化适配器
        recyclerView.adapter=adapter


    }

    override fun initData() {
        collectState(viewModel.state){state ->
            updateUI(state)
        }
    }

    private fun updateUI(state: CommentUIState) {
        adapter.submitList(state.comentData) //假设适配器有submitList方法
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.playerView.player?.release()
    }

}